package com.example.flow.biz.interceptor.approval;


import com.example.flow.constant.FlowConstant;
import com.example.flow.dao.FlowApproveApplyDao;
import com.example.flow.dao.model.FlowApproveApply;
import com.example.flow.enums.EnumApproveResult;
import com.example.flow.enums.EnumApproveStatus;
import com.example.flow.enums.EnumFinishFlag;
import com.example.flow.enums.EnumReply;
import com.example.flow.flow.FlowNodeInterceptor;
import com.example.flow.flow.core.Execution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 非进件审批结束节点拦截器
 *
 * @author safe
 * @date 2021/1/31
 */
@Service
public class EndCommonApprovalInterceptor implements FlowNodeInterceptor {
    private static Logger log = LoggerFactory.getLogger(EndCommonApprovalInterceptor.class);

    @Autowired
    private FlowApproveApplyDao flowApproveApplyDao;

    @Override
    public void intercept(Execution execution) {
        String replyCode = (String) execution.getArgs()
            .get(FlowConstant.REPLY_RESULT);
        EnumReply reply = EnumReply.find(replyCode);
        log.info("任务[{}]进入EndCommonApprovalInterceptor,结果[{}]", execution.getOrder()
            .getId(), reply);
        FlowApproveApply approveApply = flowApproveApplyDao.queryOne(null, execution.getOrder()
            .getOrderId());

        approveApply.setStatus(
            EnumReply.ADOPT == reply ? EnumApproveStatus.ADOPT.getCode() : EnumApproveStatus.REFUSE.getCode());

        approveApply.setFinishFlag(EnumFinishFlag.YES.getCode());

        switch (reply) {
            case ADOPT:
                approveApply.setApproveResult(EnumApproveResult.ADOPT.getCode());
                break;
            case REFUSE:
                approveApply.setApproveResult(EnumApproveResult.REFUSE.getCode());
                // todo 插入历史
                break;
        }

        approveApply.setUpdateTime(new Date());
        flowApproveApplyDao.updateByExampleBySelective(approveApply);
    }
}
